package Study;

public class Demo4 {

//    public static int result = 0;

    /**
     * 二分查找
     * <p>
     * 前提有序
     */


    public static void main(String[] args) {

        int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};

        Demo4 demo4 = new Demo4 ();

        int result = demo4.ArrayIndex (arr, 5);


        System.out.println ("你查找的数字——5——在数组的第" + result + "位置");
    }

    public static int ArrayIndex(int[] arr, int n)//n为需要查找的数据
    {
        int tou = 0;
        int wei = arr.length - 1;
        while (tou <= wei) {

            int mid = (tou + wei) / 2;

            if (arr[mid] == n) {
                return mid;
            } else if (arr[mid] > n) {
                tou = mid - 1;
            } else {
                wei = mid + 1;
            }
        }
        return -1;
    }

}
